<template>
	<view class="container" style="padding-bottom: 70px;">
		<!-- 搜索区域 -->
		<view class="search-collapse" v-if="checkPerms('client:examine:query')" >
			<view class="search-collapse-header" @tap="toggleSearch">
				<text class="toggle-icon">{{ showSearch ? '▲' : '▼' }}</text>
				<text class="header-text">搜索条件</text>
			</view>

			<view class="search-form" v-show="showSearch">
				<view class="form-item">
					<label>检测点位:</label>
					<input v-model="formData.monitoringPoints" placeholder="请输入检测点位" class="input" />
				</view>

				<view class="form-item">
					<label>检测项目:</label>
					<input v-model="formData.testItems" placeholder="请输入检测项目" class="input" />
				</view>

				<view class="form-item">
					<label>检测方法:</label>
					<input v-model="formData.detectionMethod" placeholder="请输入检测方法" class="input" />
					</picker>
				</view>

				<view class="form-item">
					<label>检测频次:</label>
					<input v-model="formData.monitoringFrequency" placeholder="请输入检测频次" class="input" />
					</picker>
				</view>


				<view class="form-item">
					<label>时间:</label>
					<picker mode="date" :value="formData.initiationTime" @change="onTimeChange" class="picker input">
						<view class="picker-text">{{ formData.initiationTime || '请选择时间' }}</view>
					</picker>
				</view>

				<view class="form-button">
					<button class="primary-btn" @click="submitForm"  v-if="checkPerms('client:examine:query')" >查询</button>
					<button class="reset-btn" @click="resetForm"  v-if="checkPerms('client:examine:query')">重置</button>
				</view>

			</view>
		</view>

		<!-- 任务列表 -->
		<view class="list">
			<view v-for="(item, index) in tableData" :key="index" class="list-item">
				<view class="card task-card">
					<view class="card-header task-header">
						<view class="task-id">任务编号：{{ item.taskId }}</view>
						 <span>{{getTaskFlowStatus(item.auditStatus, item.status)}}</span> 
					</view>

					<view class="card-content task-info">
						<view class="detail-row info-item">
							<view class="detail-label">项目名称：</view>
							<view class="detail-value">{{ item.taskName }}</view>
						</view>
						<view class="detail-row info-item">
							<view class="detail-label">委托单位：</view>
							<view class="detail-value">{{ item.entrustingUnit }}</view>
						</view>
						<view class="detail-row info-item">
							<view class="detail-label">受检单位：</view>
							<view class="detail-value">{{ item.testedUnit }}</view>
						</view>
						<view class="detail-row info-item">
							<view class="detail-label">检测性质：</view>
							<view class="detail-value">{{ item.detectionProperties }}</view>
						</view>
						<view class="detail-row info-item">
							<view class="detail-label">报告时间：</view>
							<view class="detail-value">{{ item.reportTime }}</view>
						</view>
					</view>
					<view class="card-actions">
						<button class="action-btn primary" @click="openDialog()"  v-if="checkPerms('client:examine:submit')"
							>提交</button>
						<button class="action-btn success" @click="gotoReturnPage(item)"  v-if="checkPerms('client:examine:reject')"
							>退回</button>
						<button class="action-btn danger" @click="viewDetails(item)"  v-if="checkPerms('client:examine:view')"
							>查看</button>
							<notice :visible="confirmDialogVisible" title="提交确认"
								 :businessType="businessType" :taskId="item.taskId" 
								 :toExamineType="'2'" :submitForm="'任务单审核'"
								  @update:visible="confirmDialogVisible = $event"/>

					</view>
				</view>
			</view>
		</view>

		<!-- 分页组件 -->
		<view class="pagination">
			<uni-pagination :page-size="formData.pageSize" :current="formData.pageNum" :total="total" show-icon
				@change="changePage" />
		</view>
	</view>
</template>

<script>
	import notice from '../common/notice/index.vue';
	import {
		add,
		toExamine,
		list,
		examineList,
		update,
		submitTask,
		receiveTask,
		rejectTask,
		selectDeptTree,
		selectUserByDeptId,
		confirmeList,
		getTaskFiles,
		selectCcName
	} from "@/api/mobilebusiness";
	import {
		getToken
	} from "@/utils/auth";
	import {
		wxLoginGetCode,
		queryAuthorize,
		queryPerms
	} from "@/api/system/wechat";

	export default {
		components: {
		    notice,  
		  },  
		data() {
			return {
				confirmDialogVisible: false, // 控制弹窗显示
				businessType: 'examine',
				// 选择器选项  
				urgencyOptions: ["普通", "加急", "特急"],
				methodOptions: ["现场采样", "送样"],
				// 索引状态  
				urgencyIndex: 0, // 初始化为0  
				methodIndex: 0, // 初始化为0 
				// 搜索表单数据  
				formData: {
					jobNumber: "",
					detectionNature: "",
					urgencyDegree: "",
					detectionMethod: "",
					monitoringPoints: "",
					initiationTime: "",
					pageNum: 1,
					pageSize: 10
				},

				// 列表数据  
				tableData: [],
				total: 0,

				// UI状态  
				showSearch: false,
				fileDialogVisible: false,
				selectedFiles: [],
				perms: '', // 提供一个默认字符串 
			};
		},

		computed: {
			// 小程序权限判断   
			hasPermission() {
				return (perm) => wx.getStorageSync('permissions')?.includes(perm)
			}
		},


		mounted() {
			this.getList();
		},
		onLoad() {
			this.queryPerms();
		},

		methods: {
			queryPerms() {
			  	queryPerms().then(response => {  
			  	    console.log("queryAuthorize + response:==" + response);  
			  	    // 确保 response 是数组，或者解析为数组  
			  	    this.perms = Array.isArray(response) ? response : JSON.parse(response);  
			  	    console.log("queryAuthorize + this.perms:==" + this.perms);  
			  	  });  
			  },
			checkPerms(perm) {  
				// 如果是管理员（admin），则跳过权限检查
				if (this.perms.includes("admin")) {
				  return true;
				}
				
			  if (!this.perms || !Array.isArray(this.perms)) {  
			    return false;  
			  }  
			  return this.perms.includes(perm);  
			},
			openDialog() {
				this.confirmDialogVisible = true; // 打开弹窗  
			},
			onTimeChange(e) {
				this.formData.initiationTime = e.detail.value;
			},
			submitForm() {
				this.getList()
			},
			// 搜索功能  
			toggleSearch() {
				this.showSearch = !this.showSearch;
			},

			getList() {
				this.loading = true;
				this.formData.queryType = "1";
				list(this.formData).then((response) => {
						console.log(response);
						this.tableData = response.rows;
						this.total = response.total;
						this.loading = false;
					})
					.catch(() => {
						this.loading = false;
						this.$message.error("获取数据失败");
					});
			},

			// 表单更新方法  
			updateForm(field, e) {
				const value = e.mp.detail?.value || e;
				this.formData[field] = value;
			},

			// 文件操作  
			async showFileDialog(item, type) {
				try {
					const {
						data
					} = await getTaskFiles({
						taskId: item.taskId,
						fileType: type
					});

					this.selectedFiles = data;
					this.fileDialogVisible = true;
				} catch (e) {
					wx.showToast({
						title: '获取文件失败',
						icon: 'error'
					});
				}
			},

			// 分页处理  
			changePage(e) {
				this.formData.pageNum = e.current;  
				this.getList();  
			},

			// 小程序下载文件  
			downloadFile(file) {
				wx.downloadFile({
					url: file.filePath,
					success: (res) => {
						wx.openDocument({
							filePath: res.tempFilePath
						});
					}
				});
			},

			// 操作按钮方法（示例）  
			uploadFiles(item) {
				wx.chooseMessageFile({
					count: 5,
					success: (res) => {
						this.uploadToServer(res.tempFiles, item.taskId);
					}
				});
			},

			gotoReturnPage(item) {
				const tuihuiFrom = "taskExamine"; 
				uni.navigateTo({
					url: `/pages/business/common/return/index?taskId=${item.taskId}&tuihuiFrom=${tuihuiFrom}`,  
				});  
			},
			viewDetails(row) {
				this.currentRecord = {
					...row
				}; // 将当前行数据赋值给 currentRecord  
				this.taskFile.taskId = this.currentRecord.taskId;
				this.taskFile.fileType = "business"
				getTaskFiles(this.taskFile).then(files => {
					this.selectedFiles = files.data
				// tiaozhuan
			 }).catch(() => {
					console.error("获取文件信息失败:", error);
					this.selectedFiles = []; // 清空文件信息  
					this.fileDialogVisible = false; // 关闭对话框   
				});
			 
			},
			
			    getTaskFlowStatus(auditStatus, status) {  
			      let auditStatusText = '';  
			      let statusText = '';  
			      // 根据 audit_status 的值设置描述  
			      switch (auditStatus) {  
			        case '0':  
			          auditStatusText = '任务单登记';  
			          break;  
			        case '1':  
			          auditStatusText = '任务单审核模块';  
			          break;  
			        case '2':  
			          auditStatusText = '采样检测业务';  
			          break;  
			        case '3':  
			          auditStatusText = '样品管理';  
			          break;  
			        case '4':  
			          auditStatusText = '实验分析';  
			          break;  
			        case '5':  
			          auditStatusText = '检测报告';  
			          break;  
			        case '6':  
			          auditStatusText = '采样检测传输';
			          break;  
			        default:  
			          auditStatusText = '未知状态';  
			      }  
			
			      // 根据 status 的值设置描述  
			      switch (status) {  
			        case '0':  
			          statusText = '未开始';  
			          break;  
			        case '1':  
			          statusText = '任务中';  
			          break;  
			        case '2':  
			          statusText = '已完成';  
			          break;  
			        default:  
			          statusText = '未知状态';  
			      }  
			
			      return `${auditStatusText} - ${statusText}`; // 返回组合后的状态描述  
			    },  
		}
	};
</script>

<style>
	.container {
		padding: 12px;
		background-color: #f3f4f7;
	}

	.search-collapse-header {
		font-size: 16px;
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 10px 12px;
		border: 1px solid #ddd;
		background-color: #fff;
		border-radius: 6px;
		margin-bottom: 10px;
	}

	.header-text {
		font-weight: bold;
	}

	.search-form {
		background-color: #fff;
		padding: 14px;
		border-radius: 6px;
	}

	.form-item {
		margin-bottom: 12px;
		display: flex;
		align-items: center;
	}

	.form-item label {
		width: 25%;
		font-size: 14px;
		color: #333;
	}

	.input {
		border: 1px solid #ddd;
		border-radius: 6px;
		padding: 8px 10px;
		flex: 1;
	}

	.picker {
		border: 1px solid #ddd;
		border-radius: 6px;
		padding: 8px 10px;
	}

	.form-button {
		display: flex;
		justify-content: space-between;
		margin-top: 12px;
	}

	.primary-btn {
		background-color: #409eff;
		color: white;
		padding: 8px 14px;
		border-radius: 6px;
		flex: 1;
		margin-right: 8px;
	}

	.reset-btn {
		background-color: #eeeeee;
		padding: 8px 14px;
		border-radius: 6px;
		color: #333;
		flex: 1;
	}

	.list {
		margin-top: 14px;
	}

	.list-item {
		background-color: #fff;
		border-radius: 6px;
		box-shadow: 0px 2px 6px rgba(0, 0, 0, 0.1);
		margin-bottom: 12px;
		padding: 14px;
	}

	.card-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
		margin-bottom: 12px;
	}

	.status-tag {
		padding: 0px 8px;
		border-radius: 12px;
		color: #fff;
	}

	.status-tag-danger {
		background-color: #f56c6c;
	}

	.status-tag-success {
		background-color: #67c23a;
	}

	.card-content {
		margin-bottom: 12px;
	}

	.detail-row {
		display: flex;
		margin-bottom: 6px;
	}

	.detail-label {
		color: #333;
		font-weight: bold;
		width: 25%;
	}

	.detail-value {
		flex: 1;
		color: #666;
	}

	.card-actions {
		display: flex;
		gap: 15px;
	}

	.action-btn {
		padding: 0px 10px;
		border: none;
		border-radius: 50px;
		font-size: 14px;
	}

	.action-btn.danger {
		background-color: #f56c6c;
		color: #fff;
	}

	.action-btn.warning {
		background-color: #e6a23c;
		color: #fff;
	}

	.action-btn.success {
		background-color: #67c23a;
		color: #fff;
	}

	.pagination {
		margin-top: 16px;
		text-align: center;
	}
</style>
